package com.rzgeo.rzmaplib.da;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.Symbol;
import com.rzgeo.rzmaplib.util.RmlUtil;
import com.rzgeo.rzmaplib.util.IRmlLoadListener;

/**
 * Created by zhanghang on 2018/1/19.
 */

public class RmlSGDBTableHolder {

    private final MapView _mapView;
    private final SQLiteDatabase _db;
    private final String _tabelName;
    private GraphicsOverlay _gl;
    private static final String kGeomtry = "geo";
    private static final String kSymbol = "symbol";
    private static final String kAttrs = "attrs";
    private static final String kGID = "GID";

    private static final String WhereUpdate = kGID + " = ";
    //    private static final String[]WhereArgs = new String[0];
    private int _maxGid = 0;


    public RmlSGDBTableHolder(MapView mapView, SQLiteDatabase db, String tabelName, int capacity, IRmlLoadListener onLoadListener) {
        _mapView = mapView;
        _gl = new GraphicsOverlay();
        _db = db;
        _tabelName = tabelName;
        ;

        _mapView.getGraphicsOverlays().add(_gl);

        new InitTask(onLoadListener).execute(_tabelName);
    }

    public GraphicsOverlay getGraphicsOverlay() {
        return _gl;
    }

    public void pushGraphic(Graphic g) {
        if (_gl.getGraphics().contains(g)) {

        } else {
            _maxGid++;
            g.getAttributes().put(kGID, _maxGid);

            ContentValues cv = new ContentValues(3);
            cv.put(kGeomtry, g.getGeometry().toJson());
            cv.put(kSymbol, g.getSymbol().toJson());
            cv.put(kAttrs, RmlUtil.Convert.map2JsonStr(g.getAttributes()));

            _db.insert(_tabelName, null, cv);
            _gl.getGraphics().add(g);

        }
    }

    public void updateGraphic(Graphic g) {
        if (_gl.getGraphics().contains(g)) {

            int GID = (int) g.getAttributes().get(kGID);

            ContentValues cv = new ContentValues(3);
            cv.put(kGeomtry, g.getGeometry().toJson());
            cv.put(kSymbol, g.getSymbol().toJson());
            cv.put(kAttrs, RmlUtil.Convert.map2JsonStr(g.getAttributes()));

            int effectCount = _db.update(_tabelName, cv, WhereUpdate + GID, null);
        } else {

        }
    }

    public void removeGraphic(Graphic g) {
        if (_gl.getGraphics().contains(g)) {
            int GID = (int) g.getAttributes().get(kGID);
            _db.delete(_tabelName, WhereUpdate + GID, null);
        }
    }

    class InitTask extends AsyncTask<String, Integer, Boolean> {

        private final IRmlLoadListener _onLoadListener;
        private boolean _success;
        private String _msg;

        public InitTask(IRmlLoadListener onLoadListener) {
            _onLoadListener = onLoadListener;

            _success = true;
            _msg = "";
        }

        @Override
        protected Boolean doInBackground(String... strings) {
            Cursor cursor = _db.query(_tabelName, new String[]{kGID, kGeomtry, kAttrs, kSymbol},
                    null, null, null, null, null);
            int iGID = cursor.getColumnIndex(kGID);
            int iGeomtry = cursor.getColumnIndex(kGeomtry);
            int iAttrs = cursor.getColumnIndex(kAttrs);
            int iSymbol = cursor.getColumnIndex(kSymbol);

            if (cursor.moveToFirst()) {
                do {
                    try {
                        int GID = cursor.getInt(iGID);
                        if(GID>_maxGid)
                            _maxGid=GID;

                        String geoStr = cursor.getString(iGeomtry);
                        String Attrs = cursor.getString(iAttrs);
                        String symbol = cursor.getString(iSymbol);

                        Graphic graphic = new Graphic(
                                Geometry.fromJson(geoStr),
                                RmlUtil.Convert.jsonToMap(Attrs),
                                Symbol.fromJson(symbol)
                        );
                        _gl.getGraphics().add(graphic);
                    }catch (Exception e){
                        _success=false;
                        RmlUtil.Log.Err(e);
                        _msg+=e.getMessage();
                    }
                }
                while (cursor.moveToNext());
            }

            cursor.close();
            return _success;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
            _onLoadListener.Loaded(_success, _msg);
        }
    }
}
